// @auth: yan rui
// @Time: 2024-11-01 17:37:26
// @desc: 权限校验封装，如果没有权限，则弹出权限申请弹框

import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import '/utils/dialog.dart';

/// 封装权限校验
class CheckPermission {
  /// 判断是否权限已被允许
  static Future<bool> _checkPermission(Permission permission, String message) async {
    final status = await permission.status;

    /// 权限以已允许
    if (status.isGranted) {
      return true;
    }

    /// 权限被拒绝，提示用户允许权限
    if (status.isDenied) {
      _showPermissionDialog(message);
      return false;
    }

    /// 权限被永久拒绝，引导用户去设置中手动开启权限
    if (status.isPermanentlyDenied) {
      _showPermissionDialog(message);
      return false;
    }

    return false;
  }

  /// 打开权限设置的提示框
  static _showPermissionDialog(String msg) async{

    BuildContext context = GlobalKey().currentContext!;

    final bool hasPermission = await customShowDialog(
        context,
        title: '权限请求',
        tipText: msg,
        confirmText: '设置'
    ) ?? false;
    if (context.mounted && hasPermission) {
      openAppSettings();
    }
  }

  /// 相机相册 权限检查和请求
  static Future<bool> photos({String message = '暂无相册权限，请前往设置开启权限'}) async {
    bool isGranted = await _checkPermission(Permission.photos, message);
    return isGranted;
  }

  /// 相机 权限检查和请求
  static Future<bool> camera({String message = '暂无相机权限，请前往设置开启权限'}) async {
    bool isGranted = await _checkPermission(Permission.camera, message);
    return isGranted;
  }

  /// 麦克风 权限检查和请求
  static Future<bool> microphone({String message = '暂无麦克风权限，请前往设置开启权限'}) async {
    bool isGranted = await _checkPermission(Permission.microphone, message);
    return isGranted;
  }

  /// 存储 权限检查和请求
  static Future<bool> storage({String message = '暂无手机存储权限，请前往设置开启权限'}) async {
    bool isGranted = await _checkPermission(Permission.storage, message);
    return isGranted;
  }
}
